#include <dogon/gltools.h>
#include <assert.h>
#include <stdio.h>

int is_extension_supported( const char *extension )
{
    const GLubyte *extensions = NULL;
    const GLubyte *start;
    GLubyte *where, *terminator;

    /* Extension names should not have spaces. */
    where = (GLubyte *) strchr(extension, ' ');
    if (where || *extension == '\0')
        return 0;

    extensions = glGetString(GL_EXTENSIONS);

    /* It takes a bit of care to be fool-proof about parsing the
    OpenGL extensions string. Don't be fooled by sub-strings, etc. */
    start = extensions;
    for (;;) {
        where = (GLubyte *) strstr((const char *) start, extension);
        if (!where)
            break;
        terminator = where + strlen(extension);
        if (where == start || *(where - 1) == ' ')
            if (*terminator == ' ' || *terminator == '\0')
                return 1;
        start = terminator;
    }
    return 0;
}



int split_shader(char* shader_source, char** vertex_shader, char** fragment_shader)
{
	char *s, *eos_vertex_shader;

	assert(shader_source != 0 && vertex_shader != 0 && fragment_shader != 0);

	for (s = (*vertex_shader) = shader_source; *s; s++)
	{
		if (*s == '\n' || *s == '\r')
		{
			if (s[0] == '\n' && s[1] == '\r') s++;
			else if (s[0] == '\r' && s[1] == '\n') s++;

			++s;

			if (*s == '%' && s[1] == '%') {
				*s = '\0'; // terminate vertex_shader
				eos_vertex_shader = s;
				s+=2; // skip second '%'

				while (*s != '\0' && *s != '\n' && *s != '\r') s++;
				if (*s == '\0') {
					// empty fragment shader
					(*fragment_shader) = eos_vertex_shader;
					return 0;
				}
				else {
					if ((s[0] == '\n' && s[1] == '\r') || (s[0] == '\r' && s[1] == '\n')) s++;

					++s;

					(*fragment_shader) = s;
					return 0;
				}
			}
			else
				--s;
		}
	}

	return 1; /* empty input string */
}





char* info_log(GLhandleARB obj)
{
    int infologLength = 0;
    int charsWritten  = 0;
    GLcharARB *infoLog;

	glGetObjectParameterivARB(obj, GL_OBJECT_INFO_LOG_LENGTH_ARB, &infologLength);

    if (infologLength > 0)
    {
        infoLog = (GLcharARB*)malloc(infologLength);
        
		if (infoLog == NULL) return NULL;

        glGetInfoLogARB(obj, infologLength, &charsWritten, infoLog);

		return infoLog;
    }

	return NULL;
}

